package com.happyfamily.springboot.crowdsourcingplatform.service.guo.impl;

import com.happyfamily.springboot.crowdsourcingplatform.dao.guo.FriendShipDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.guo.FrontNeedDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.guo.ServiceDao;
import com.happyfamily.springboot.crowdsourcingplatform.model.Work;
import com.happyfamily.springboot.crowdsourcingplatform.service.guo.PictureService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class PictureServiceImpl implements PictureService
{

	@Autowired(required = false)
	FriendShipDao friendShipDao;


	@Override
	public boolean uploadPicture(HttpServletRequest request, MultipartFile file)
	{
		boolean flag=false;
		String name="";
		String theurl=request.getParameter("theurl");
		String titles=request.getParameter("titles");
		try
		{
			SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			String account=securityContextImpl.getAuthentication().getName();



			File f= new File("src/main/resources/static/friendimages");

			System.out.println(file);
			name=file.getOriginalFilename();
			System.out.println(name);
			int index=name.lastIndexOf(".");
			String type=name.substring(index+1);
			File newFile=new File(f.getAbsolutePath()+"/"+name);
			int x=1;
			while(newFile.exists())
			{
				name=name.substring(0,index);
				name=name+"副本"+x+"."+type;
				newFile=new File(f.getAbsolutePath()+"/"+name);
				x++;
			}
			file.transferTo(newFile);

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

		System.out.println("当前文件名字"+name);

		int n=friendShipDao.addFriendLink(theurl,"/friendimages/"+name,titles,"未展示");
		if (n>0){
			flag=true;
		}
		return flag;
	}
}
